import sys
import os
from cx_Freeze import setup, Executable
from src.config import version_

sys.path.append(r'../')
include_files = ['src', 'config.ini']
excludes_packages = ["tkinter", "test", 'unittest', 'multiprocessing', 'msilib', 'lib2to3', '_distutils_hack',
                     'greenlet', 'html', 'http', 'importlib_metadata', 'pydoc_data', 'setuptools', 'pkg_resources',
                     'libcrypto-1_1']
packages = ['PyQt5', 'numpy', 'pandas', 'pymysql', 'sqlalchemy', 'configobj']

base = 'Win32GUI' if sys.platform == 'win32' else None

options = {
    'build_exe': {
        # 'includes': ["pandas", "numpy", "openpyxl"],
        'include_files': include_files,
        'packages': packages,
        "excludes": excludes_packages,
    }
}

executables = [
    Executable('PDMs.py', base=base, icon='icon/logo.ico'),
]


def transform(path, flag):
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path, file)) and os.path.splitext(file)[-1] == '.py' or file in flag:
            os.remove(os.path.join(path, file))
            print('deleting {}'.format(os.path.join(path, file)))
        elif os.path.isdir(os.path.join(path, file)) and file == '__pycache__':
            for pyc_file in os.listdir(os.path.join(path, file)):
                pyc_file_path = os.path.join(path, file, pyc_file)
                if os.path.isfile(pyc_file_path) and os.path.splitext(pyc_file)[-1] == '.pyc':
                    rename = pyc_file.replace('.cpython-39', '', 1)
                    os.rename(pyc_file_path, os.path.join(path, rename))
                    print('moving {} to {}'.format(os.path.join(path, rename), pyc_file_path))

    for root, dirs, files in os.walk(path):
        for _dir in dirs:
            if not os.listdir(os.path.join(root, _dir)):
                os.rmdir(os.path.join(root, _dir))


def customer():
    # 自定义函数
    print('transforming py to pyc ...')
    print('deleting py files...')
    transform('build\\exe.win-amd64-3.9\\src', [])
    transform('build\\exe.win-amd64-3.9\\PyQt5.uic.widget-plugins', [])
    transform('build\\exe.win-amd64-3.9\\lib\\\PyQt5', ['python3.dll', 'python39.dll'])


setup(
    name="PDMs",
    options=options,
    author='YanMing',
    version=version_,
    executables=executables,
    author_email='476588294@qq.com',
    description="Product Data Management System",
    zip_safe=False
)
customer()
